from rest_framework_simplejwt.serializers import TokenObtainPairSerializer, TokenRefreshSerializer
from rest_framework import serializers
from rest_framework.serializers import ValidationError
from apps.users.models import User, Permission, RolePermission, Role

from utils.base import BaseSerializer


class LoginSerializer(TokenObtainPairSerializer):

    def validate(self, attr):
        data = super().validate(attr)
        data['token_refresh'] = data.pop('refresh')
        data['token_access'] = data.pop('access')
        data['user_id'] = self.user.id
        data['user_name'] = self.user.username
        data['role_id'] = self.user.role_id
        return data


class PermissionSerializer(BaseSerializer):

    class Meta:
        model = Permission
        fields = '__all__'


class RoleSerializer(BaseSerializer):
    role_permissions = serializers.SerializerMethodField()

    class Meta:
        model = Role
        fields = ['id', 'name', 'create_time', 'update_time', 'users', 'permissions', 'role_permissions',
                  'update_by_name', 'create_by_name']

    def get_role_permissions(self, obj):
        role_permissions = obj.rolepermission_set.select_related('permission').all()
        permission_serializer = RolePermissionListSerializer(role_permissions, many=True)
        return permission_serializer.data


class RolePermissionListSerializer(BaseSerializer):
    permission = PermissionSerializer(read_only=True)

    class Meta:
        model = RolePermission
        fields = '__all__'


class RolePermissionSerializer(BaseSerializer):

    # permission_id = serializers.
    # role = RoleSerializer()

    class Meta:
        model = RolePermission
        fields = '__all__'


class MyTokenRefreshSerializer(TokenRefreshSerializer):

    def validate(self, attr):
        data = super().validate(attr)
        data['token_access'] = data.pop('access')
        return data


class RoleNameSerializer(BaseSerializer):
    class Meta:
        model = Role
        fields = ['id', 'name']


class UserNameSerializers(BaseSerializer):

    class Meta:
        model = User
        fields = ['username', 'id']


class UserSerializers(BaseSerializer):
    password_confirm = serializers.CharField(label='确认密码', help_text='确认密码', write_only=True, required=True)
    role_name = serializers.CharField(source='role.name', read_only=True)
    role_info = RoleSerializer(source='role', read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'password_confirm', 'email', 'role', 'create_time', 'update_time',
                  'role_name', 'role_info', 'create_by_name', 'update_by_name',]

    def validate(self, attrs):
        password = attrs.get('password')
        password_confirm = attrs.pop('password_confirm')

        if password and password_confirm != password:
            raise ValidationError('密码和确认密码不一致')

        return attrs

    def create(self, validated_data):
        obj = super().create(validated_data)
        obj.set_password(obj.password)
        obj.save()
        return obj

    def update(self, instance, validated_data):
        instance = super().update(instance, validated_data)
        instance.set_password(validated_data['password'])
        instance.save()
        return instance
